#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QPushButton>
#include <QtGui/QFont>
#include <QtGui/QMessageBox>
#include <QtSql/QSqlError>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>
#include <QtCore/QVariant>
#include <QValidator>
#include <QAction>
#include <QDebug>
#include <QTimer>
#include <QTextEdit>
#include <QApplication>
#include <QDesktopWidget>

#include "boardregdialog.h"
#include "passworddialog.h"
#include "reginfodialog.h"
#include "type.h"

BoardRegDialog::BoardRegDialog(QWidget *parent)
    : QDialog(parent)
{
    pollingStartTimer15s = new QTimer(this);
    pollingStartTimer15s->setInterval(30000);//15s
    pollingStartTimer15s->setSingleShot(true);
    connect(pollingStartTimer15s,SIGNAL(timeout()),this,SIGNAL(cancelPushButtonClicked()));
    timeLeft = 30;

    timer1s = new QTimer(this);
    timer1s->setInterval(1000);//1s
    connect(timer1s,SIGNAL(timeout()),this,SLOT(updateTimeLabelSlot()));

    QFont f("unifont", 12, QFont::Light);
    timeLabel = new QLabel(this);
    timeLabel->setText(tr("%1秒后将跳过登记，开始巡检").arg(pollingStartTimer15s->interval()/1000));
    timeLabel->setAlignment(Qt::AlignCenter);
    timeLabel->setFont(f);
    timeLabel->setGeometry(QRect(20,220,350,30));

    infoLabel = new QLabel(this);
    infoLabel->setAlignment(Qt::AlignCenter);
    infoLabel->setFont(f);
    infoLabel->setVisible(false);
    infoLabel->setGeometry(QRect(0,40,400,60));

//    backgroundLabel = new QLabel(this->parentWidget());
//    backgroundLabel->setPixmap(QPixmap(":/image/background.PNG"));
//    backgroundLabel->setGeometry(QRect(0,0 ,800,600));
//    backgroundLabel->setVisible(false);

    okToPollingButton = new QPushButton(tr("确定"),this);
    okToPollingButton->setGeometry(QRect(160,150,80,35));
    okToPollingButton->setVisible(false);
    connect(okToPollingButton,SIGNAL(clicked()),this,SIGNAL(regAllOverSignal()));

    createEscapeAction();
    createSingleBoardDialog();

    this->setFixedSize(500,300);
    setWindowTitle(tr("接口板登记"));

    connect(this,SIGNAL(cancelPushButtonClicked()),this,SLOT(stopTimerSlot()));
    connect(this->parentWidget(), SIGNAL(closedialog()), this, SLOT(close()));




//    isSingleRegFlag = false;

//    infoLabel = new QLabel(this);
////    infoLabel->setText(tr("是否重新登记？\n如果不需要重新登记，请点击“取消”，开始巡检\n"));
//    infoLabel->setAlignment(Qt::AlignCenter);
////    QFont f("unifont", 12, QFont::Light);
//    infoLabel->setFont(f);
//    infoLabel->setVisible(false);

//    okPushButton = new QPushButton(tr("确定"),this);
//    cancelPushButton = new QPushButton(tr("取消"),this);
//    infoLabel->setGeometry(QRect(20,40,350,60));
//    okPushButton->setGeometry(QRect(100,150,80,35));
//    cancelPushButton->setGeometry(QRect(200,150,80,35));

//    okToPollingButton = new QPushButton(tr("确定"),this);
//    okToPollingButton->setGeometry(QRect(160,150,80,35));
//    okToPollingButton->setVisible(false);

//    connect(this,SIGNAL(cancelPushButtonClicked()),this,SLOT(stopTimerSlot()));
//    //connect(this,SIGNAL(okPushButtonClicked()),this,SLOT(stopTimerSlot()));
//    connect(okPushButton,SIGNAL(clicked()),this,SIGNAL(okPushButtonClicked()));
//    connect(cancelPushButton,SIGNAL(clicked()),this,SIGNAL(cancelPushButtonClicked()));
//    connect(okToPollingButton,SIGNAL(clicked()),this,SIGNAL(regAllOverSignal()));
//    connect(this->parentWidget(), SIGNAL(closedialog()), this, SLOT(close()));

}

void BoardRegDialog::createSingleBoardDialog()
{
    //isSingleRegFlag = true;
    setWindowTitle(tr("接口板登记设置"));
    QFont f("unifont", 12, QFont::Light);
    singleRegInfoLabel = new QLabel(this);
    singleRegInfoLabel->setText(tr(">>单接口板登记 : 请输入要登记的接口板号,并点击[确定]."));
    //singleRegInfoLabel->setAlignment(Qt::AlignCenter);
    singleRegInfoLabel->setFont(f);
    singleRegInfoLabel->setGeometry(QRect(10,20,420,40));

    singleBoardNumLabel = new QLabel(this);
    singleBoardNumLabel->setText(tr("接口板号 :"));
    singleBoardNumLabel->setFont(f);
    singleBoardNumLabel->setGeometry(QRect(70,70,70,24));

    singleBoardNumLineEdit = new QLineEdit(this);
    singleBoardNumLineEdit->setGeometry(QRect(160,70,60,27));
    singleBoardNumLineEdit->setValidator(new QIntValidator(1,34,this));
    singleBoardNumLineEdit->setText(tr("1"));

    singleOkPushButton = new QPushButton(tr("确定"),this);
    singleOkPushButton->setGeometry(QRect(250,70,85,27));

    allRegInfoLabel = new QLabel(this);
    allRegInfoLabel->setText(tr(">>全体接口板登记:请点击下方按钮; 点击[取消]按钮，开始巡检"));
    allRegInfoLabel->setGeometry(QRect(10,120,480,40));
    allRegInfoLabel->setFont(f);

    allRegPushButton = new QPushButton(tr("全体接口板登记"),this);
    allRegPushButton->setGeometry(QRect(70,170,140,27));

    regCancelPushButton = new QPushButton(tr("取消"),this);
    regCancelPushButton->setGeometry(QRect(250,170,85,27));

    regInfoText = new QTextEdit(this);
    regInfoText->setGeometry(QRect(10, 60, 580, 380));
    regInfoText->setReadOnly(true);
    regInfoText->setVisible(false);

    //connect(singleOkPushButton,SIGNAL(clicked()),this,SLOT(emitSingleBoardNum()));
    //connect(allRegPushButton,SIGNAL(clicked()),this,SIGNAL(okPushButtonClicked()));
    connect(singleOkPushButton,SIGNAL(clicked()),this,SLOT(signalRegConfirmSlot()));
    connect(allRegPushButton,SIGNAL(clicked()),this,SLOT(allRegConfirmSlot()));
    connect(regCancelPushButton,SIGNAL(clicked()),this,SIGNAL(cancelPushButtonClicked()));
    connect(this->parentWidget(), SIGNAL(closedialog()), this, SLOT(close()));
}

void BoardRegDialog::signalRegConfirmSlot()
{
    PasswordDialog password(6, this);
    password.exec();
    if (password.matchFlag)
    {
        int num = singleBoardNumLineEdit->text().toInt();
        emit singleBoardNumSignal(num);
        qDebug()<<"signel board to reg is: "<<num;
    }
}

void BoardRegDialog::allRegConfirmSlot()
{
    PasswordDialog password(6, this);
    password.exec();
    if (password.matchFlag)
    {
        emit okPushButtonClicked();
    }
}

void BoardRegDialog::stopTimerSlot()
{
    timeLabel->setVisible(false);
    pollingStartTimer15s->stop();
    timer1s->stop();
}
void BoardRegDialog::statrTimer15s()
{
    timer1s->start();
    pollingStartTimer15s->start();
    qDebug()<<"in boardRegDialog:15stimer start";
}
void BoardRegDialog::updateTimeLabelSlot()
{
    timeLeft -= 1;
    timeLabel->setVisible(true);
    timeLabel->setText(tr("%1秒后将跳过登记，开始巡检").arg(timeLeft));//setText(QString(tr()));

}

void BoardRegDialog::regStartMessage()
{
    //qDebug()<<"*************************************reg-start-message";
    //if(isSingleRegFlag)//不管是单接口登记还是全体接口板登记，都隐藏
    this->setFixedSize(400,240);
    stopTimerSlot();
    setSignalVisibleFalse();
    infoLabel->setText("接口板登记中...");
    infoLabel->setAlignment(Qt::AlignCenter);
    infoLabel->setVisible(true);
//    okPushButton->setVisible(false);
//    cancelPushButton->setVisible(false);
    okToPollingButton->setVisible(false);
}

void BoardRegDialog::regFaultMessage()
{
    QMessageBox *box = new QMessageBox(tr("接口板登记"),
                                       tr("登记出错：can设备打开失败..."),
                                       QMessageBox::Information,
                                       QMessageBox::Ok,
                                       QMessageBox::NoButton,
                                       QMessageBox::NoButton,
                                       this);
    box->setAttribute(Qt::WA_DeleteOnClose);
    connect(this->parentWidget(), SIGNAL(closedialog()), box, SLOT(close()));
    box->exec();
}

void BoardRegDialog::currentRegBoardSlot(int i)
{
    //qDebug()<<"*****************************currentRegBoardSlot";
    this->setFixedSize(400,240);
    infoLabel->setVisible(true);
    infoLabel->setText(tr("%1 号接口板登记中...").arg(i));
    infoLabel->setAlignment(Qt::AlignCenter);
    setSignalVisibleFalse();
//    if(isSingleRegFlag)
//    {
//        setSignalVisibleFalse();
//    }
}
void BoardRegDialog::setSignalVisibleFalse()
{
    singleRegInfoLabel->setVisible(false);
    allRegInfoLabel->setVisible(false);
    singleBoardNumLabel->setVisible(false);
    singleBoardNumLineEdit->setVisible(false);
    singleOkPushButton->setVisible(false);
    allRegPushButton->setVisible(false);
    regCancelPushButton->setVisible(false);

}
void BoardRegDialog::setSignalVisibleTrue()
{
    singleRegInfoLabel->setVisible(true);
    allRegInfoLabel->setVisible(true);
    singleBoardNumLabel->setVisible(true);
    singleBoardNumLineEdit->setVisible(true);
    singleOkPushButton->setVisible(true);
    allRegPushButton->setVisible(true);
    regCancelPushButton->setVisible(true);

}
void BoardRegDialog::regOverSlot(int boardRegNum)
{
    //qDebug()<<"****************************************regOverSlot";
    infoLabel->setGeometry(QRect(0, 5, 600, 60));
    infoLabel->setText(tr("登记结果:共%1个接口板在线。按下 [确定] 开始巡检...").arg(boardRegNum));
    infoLabel->setAlignment(Qt::AlignCenter);
    infoLabel->setVisible(true);
//    okPushButton->setVisible(false);
//    cancelPushButton->setVisible(false);

    regInfoText->setVisible(true);
    readInfo(regInfoText);

    okToPollingButton->setGeometry(QRect(240, 450, 100, 24));
    okToPollingButton->setVisible(true);
    okToPollingButton->setFocus();

    this->setFixedSize(600,480);
    this->setGeometry(QRect(100, 30, 600, 480));
    qDebug()<<"resize after move.";
}


void BoardRegDialog::singleRegOverSlot(int boardnum)
{
    //qDebug()<<"****************************************singleRegOverSlot";
    setSignalVisibleFalse();

    QSqlDatabase::database().transaction();
    QSqlQuery query;
    query.setForwardOnly(true);
    query.exec(QString("select * from iobrinfo WHERE id = %1").arg(boardnum));
    while (query.next())
    {
        if(query.value(1).toBool())
            infoLabel->setText(tr("%1号接口板登记结束,接口板在线！ 按下 [确定] 开始巡检").arg(boardnum));
        else
            infoLabel->setText(tr("%1号接口板登记结束,接口板不在线！ 按下 [确定] 开始巡检").arg(boardnum));
    }
    QSqlDatabase::database().commit();

    okToPollingButton->setGeometry(QRect(240, 450, 100, 24));
    okToPollingButton->setVisible(true);
    okToPollingButton->setFocus();

    infoLabel->setGeometry(QRect(0, 5, 600, 60));
    infoLabel->setAlignment(Qt::AlignCenter);
    infoLabel->setVisible(true);

    regInfoText->setVisible(true);
    readInfo(regInfoText);
    this->setFixedSize(600,480);
    this->setGeometry(QRect(100, 30, 600, 480));

}

void BoardRegDialog::readInfo( QTextEdit * textEdit)
{
    devicetyep_map.clear();
    int host = 1;
    int iobr = 0;
    int loop = 0;
    int node = 1;
    int registerNodenum = 0;
    char iobrinfo[5];
    char registerNodenuminfo[5];
    memset(iobrinfo, 0, 5);
    memset(registerNodenuminfo, 0 ,5);
    QString text;

    QSqlDatabase::database().transaction();
    QSqlQuery query;
    query.setForwardOnly(true);
    query.exec(QString("select * from iobrinfo WHERE iobrregist = 'true'"));
    while (query.next())
    {
        iobr = query.value(0).toInt();
        if(iobr <= 32)
        {
            sprintf(iobrinfo, "%02d", iobr);
            text += tr("%1板:").arg(iobrinfo);
            QSqlQuery query1;
            query1.setForwardOnly(true);
            for (loop=1;loop<=4;loop++)
            {
                registerNodenum = 0;
                query1.exec(QString("select * from unitset WHERE unitid >= %1 AND unitid <= %2").arg((host << 24) | (iobr << 16) | (loop << 8) | node)
                            .arg((host << 24) | (iobr << 16) | (loop << 8) | 0xFF));
                while(query1.next())
                {
                    if (query1.value(1).toBool() == true)
                    {
                        registerNodenum++;
                        int key = ((query1.value(7).toInt() >> 8) & 0xFF);
                        //                        qDebug()<<"key"<<key;
                        if(((query1.value(7).toInt() >> 8) & 0xFF) != 0xFF)
                        {
                            int value = devicetyep_map[key];
                            value = value + 1;
                            devicetyep_map.insert(key, value);
                            //                            qDebug()<<"devicetyep_map.contains(key)"<<devicetyep_map.contains(key);
                            //                            qDebug()<<"devicetyep_map.value(key,0)"<<devicetyep_map.value(key,0);
                            //                            devicetyep_map[key] =value + 1;
                            //                            qDebug()<<"devicetyep_map[key]"<<devicetyep_map[key];
                        }
                        //                        QMap<int,int>::iterator i = devicetyep_map.begin();
                        //                        while (i != devicetyep_map.end())
                        //                        {
                        //                            qDebug()<<"devicetyep_map.key()"<< i.key();
                        //                            qDebug()<<"devicetyep_map.key()"<< i.value();
                        //                          ++i;
                        //                        }
                    }
                }
                sprintf(registerNodenuminfo, "%03d", registerNodenum);
                text += tr("%2回路%3在线  ").arg(loop).arg(registerNodenuminfo);
            }
        }
        else if(iobr == 33)
        {
            sprintf(iobrinfo, "%02d", iobr);
            text += tr("%1板:").arg(iobrinfo);
            QSqlQuery query1;
            query1.setForwardOnly(true);
            int loop=1;

            registerNodenum = 0;
            query1.exec(QString("select * from unitset WHERE unitid >= %1 AND unitid <= %2").arg((host << 24) | (iobr << 16) | (loop << 8) | node)
                        .arg((host << 24) | (iobr << 16) | (loop << 8) | 0xFF));
            while(query1.next())
            {
                if (query1.value(1).toBool() == true)
                {
                    registerNodenum++;
                }
            }
            sprintf(registerNodenuminfo, "%03d", registerNodenum);
            text += tr("%3个楼显在线  ").arg(registerNodenuminfo);

        }
        else if(iobr == 34)
        {
            sprintf(iobrinfo, "%02d", iobr);
            text += tr("%1板:").arg(iobrinfo);
            QSqlQuery query1;
            query1.setForwardOnly(true);

            registerNodenum = 0;
            query1.exec(QString("select count(*) from zhikonginfo WHERE zhikongregist = 'true'"));
            while(query1.next())
            {
                registerNodenum =  query1.value(0).toInt() ;
            }
            if(registerNodenum > 0)
            {
                sprintf(registerNodenuminfo, "%03d", registerNodenum);
                text += tr("%3个直控盘在线  ").arg(registerNodenuminfo);
            }

            QSqlQuery query2;
            query2.setForwardOnly(true);

            query2.exec(QString("select count(*) from zongxianinfo WHERE zongxianregist = 'true'"));
            while(query2.next())
            {
                registerNodenum =  query2.value(0).toInt() ;
            }
            if(registerNodenum > 0)
            {
                sprintf(registerNodenuminfo, "%03d", registerNodenum);
                text += tr("%3个总线盘在线  ").arg(registerNodenuminfo);
            }

        }
        text += "\n";
    }
    QSqlDatabase::database().commit();
    QMap<int,int>::iterator i = devicetyep_map.begin();
    while (i != devicetyep_map.end())
    {
        qDebug()<<"devicetyep_map.key()"<< i.key();
        qDebug()<<"devicetyep_map.key()"<< i.value();
        text += Type::char_danyuan(i.key());
        text += tr("%4个在线  ").arg(i.value());
        text += "\n";
        ++i;
    }
    textEdit->setPlainText(text);

}

void BoardRegDialog::emitSingleBoardNum()
{
    int num = singleBoardNumLineEdit->text().toInt();
    emit singleBoardNumSignal(num);
    qDebug()<<"signel board to reg is: "<<num;

}

void BoardRegDialog::refreshDialog()
{
//    backgroundLabel->setVisible(true);

//    infoLabel->setVisible(false);
////    okPushButton->setVisible(false);
////    cancelPushButton->setVisible(false);
//    okToPollingButton->setVisible(false);

//    setSignalVisibleTrue();
//    this->exec();

//    backgroundLabel->setVisible(false);
}

void BoardRegDialog::createEscapeAction()
{
    //qDebug()<<"in boardRegDialog:escape clicked! emit cancelPushButtonClicked signal.";
    escapeAction = new QAction (this);
    escapeAction->setShortcut (/*Qt::CTRL+*/Qt::Key_Escape);
    connect(escapeAction, SIGNAL(triggered()), this, SIGNAL(cancelPushButtonClicked()));
    this->addAction(escapeAction);
}

BoardRegDialog::~BoardRegDialog()
{
    delete(infoLabel);
//    delete(okPushButton);
//    delete(cancelPushButton);
    delete(singleRegInfoLabel);
    delete(allRegInfoLabel);
    delete(singleBoardNumLabel);
    delete(singleBoardNumLineEdit);
    delete(singleOkPushButton);
    delete(allRegPushButton);
    delete(regCancelPushButton);
    delete(escapeAction);
    delete(regInfoText);
}
